import React from 'react';

function widthHoc(WrappedComponent) {
  return class extends React.PureComponent {
    state = {
      windowWidth : 0
    }

    setWindowWidth = () => {
      this.setState({
        windowWidth : window.innerWidth
      })
    }

    componentDidMount(){
      window.addEventListener('resize',this.setWindowWidth)
    }

    componentWillUnmount() {
      window.removeEventListener('resize',this.setWindowWidth)
    }

    render() {
      return (
        <WrappedComponent {...this.props} windowWidth={this.state.windowWidth} />
      )
    }
  }

  // @TODO：改写返回值，实现高阶组件
  
}

// @widthHoc
class Demo extends React.Component {

  render() {
    return <div>浏览器宽度：{this.props.windowWidth}</div>;
  }
}

const User = (props) => <div>User: {props.windowWidth}</div>

const WidthDemo = widthHoc(Demo)
const WidthUser = widthHoc(User)

export default () => {
  return(
    <>
      <WidthDemo/>
      <WidthUser/>
    </>
  )
}


